package com.d404.server;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.junit.Test;

import com.alibaba.fastjson.JSON;

import im.beans.Classify;
import im.beans.Classify_User;
import im.beans.User;
import im.notify.server.Notify;
import manager.MessageManager;
import manager.PersistentManager;

/**
 * Servlet implementation class DealAddFriend
 */
// @WebServlet("/DealAddFriend")
public class DealAddFriend extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public DealAddFriend() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String userID = request.getParameter("userID");
		String userName = request.getParameter("userName");
		String friendID = request.getParameter("friendID");
		String friendName = request.getParameter("friendName");
		String state = request.getParameter("state");

		boolean isRight = true;
		SessionFactory sf = PersistentManager.sharemanager().getSessionFactory();
		Session session = sf.getCurrentSession();
		Transaction tx = session.beginTransaction();
		// 返回好友信息
		BackUser bu = null;
		User friend = null;

		try {
			// 写入添加好友表
			Query q = session.createQuery(
					"update AddNewFriends af set af.state = ? where af.asker_id =  ? and af.be_asked_id = ? ");
			q.setParameter(0, Integer.parseInt(state));
			q.setParameter(1, Long.parseLong(friendID));
			q.setParameter(2, Long.parseLong(userID));
			q.executeUpdate();

			// 判断是否同意
			if (Integer.parseInt(state) == AddFriend.MsgBack.State.USER_ACCEPT) {
				// 若同意，互相添加为好友
				Query q2 = session.createQuery("from Classify cf where cf.classifyName = ? and cf.ower = ?");
				q2.setParameter(0, "未分组");
				User u = new User();
				u.setId(Long.parseLong(userID));
				q2.setParameter(1, u);

				User u2 = new User();
				u2.setId(Long.parseLong(friendID));

				ArrayList<Classify> csf = (ArrayList<Classify>) q2.list();
				for (Classify cs : csf) {
					Classify_User cu = null;

					// 若CU存在
					Query qCU = session.createQuery("from Classify_User cu where cu.classify = ? and cu.user = ?");
					qCU.setParameter(0, cs);
					qCU.setParameter(1, u2);
					List<Classify_User> cus = qCU.list();
					for (Classify_User tempCU : cus) {
						cu = tempCU;
					}
					// 用户不在分组，则添加
					if (cu == null) {
						cu = new Classify_User();
						cu.setClassify(cs);
						cu.setUser(u2);
						session.save(cu);
					}

				}

				Query q3 = session.createQuery("from Classify cf where cf.classifyName = ? and cf.ower = ?");
				q3.setParameter(0, "未分组");
				q3.setParameter(1, u2);

				ArrayList<Classify> csf2 = (ArrayList<Classify>) q3.list();
				for (Classify cs : csf2) {
					Classify_User cu = null;

					// 若CU存在
					Query qCU = session.createQuery("from Classify_User cu where cu.classify = ? and cu.user = ?");
					qCU.setParameter(0, cs);
					qCU.setParameter(1, u);
					List<Classify_User> cus = qCU.list();
					for (Classify_User tempCU : cus) {
						cu = tempCU;
					}
					// 用户不在分组，则添加
					if (cu == null) {
						cu = new Classify_User();
						cu.setClassify(cs);
						cu.setUser(u);
						session.save(cu);
					}

				}

				// TODO 获取好友信息，返回
				friend = (User) session.get(User.class, Long.parseLong(friendID));
				bu = new BackUser();
				bu.setAccount(friend.getAccount());
				bu.setId(friend.getId());
				bu.setUser(friend);
			}
			// 拒绝添加
			else {

			}
			session.getTransaction().commit();
			//  处理添加好友
			if (Integer.parseInt(state) == AddFriend.MsgBack.State.USER_ACCEPT) {
//				MessageManager.sendSimpleMessage(friendName, Notify.FRIEND_DEAL_AGREE);
				Notify.BeAgree beAgree = new Notify.BeAgree();
				beAgree.setAccount(userName);
				MessageManager.sendSimpleMessage(friendName, JSON.toJSONString(beAgree));
			}else
			{
				Notify.BeRufused beRufused = new Notify.BeRufused();
				beRufused.setAccount(userName);
				MessageManager.sendSimpleMessage(friendName, JSON.toJSONString(beRufused));
			}
			
		} catch (Exception e) {
			tx.rollback();
			isRight = false;
			e.printStackTrace();
		} finally {
		}

		response.setCharacterEncoding("UTF-8");
		MsgBack back = new MsgBack();
		if (isRight) {
			back.setStatus(MsgBack.SUCCESS);
			back.setUser(bu);
		} else {
			back.setStatus(MsgBack.FAILD);
		}
		System.out.println(JSON.toJSONString(back));
		response.getWriter().append(JSON.toJSONString(back));
	}


	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

	public static class MsgBack {
		public static final String SUCCESS = "1";
		public static final String FAILD = "2";

		String status;
		BackUser user;

		public String getStatus() {
			return status;
		}

		public void setStatus(String status) {
			this.status = status;
		}

		public BackUser getUser() {
			return user;
		}

		public void setUser(BackUser user) {
			this.user = user;
		}

	}

	/*
	 * 返回用户信息
	 */
	public static class BackUser {
		private long id;
		// 用户账号
		private String account;

		private User user;

		public User getUser() {
			return user;
		}

		public void setUser(User user) {
			this.user = user;
		}

		public long getId() {
			return id;
		}

		public void setId(long id) {
			this.id = id;
		}

		public String getAccount() {
			return account;
		}

		public void setAccount(String account) {
			this.account = account;
		}
	}

	@Test
	public void test() {
		MsgBack b = new MsgBack();
		BackUser bu = new BackUser();
		b.setUser(null);
		b.setStatus(null);

		System.out.println(JSON.toJSONString(b));
	}
}
